package models;

import static akka.pattern.Patterns.ask;
import static java.util.concurrent.TimeUnit.SECONDS;

import com.fasterxml.jackson.databind.JsonNode;

import models.msgs.AddPlayer;
import models.msgs.Join;
import models.msgs.Start;
import play.libs.Akka;
import play.mvc.WebSocket;
import scala.concurrent.Await;
import scala.concurrent.duration.Duration;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;

public class Gra extends UntypedActor{
	private static ActorRef stol;
	private static ActorRef gra = Akka.system().actorOf(Props.create(Gra.class));
	private static int iloscObecnych = 0;
	private static int iloscGraczy;
	
	public static void create(int _iloscGraczy, int iloscBotow, int poczatkowe, int wpisowe){
		iloscGraczy = _iloscGraczy;
		iloscObecnych = iloscBotow;
		stol = Akka.system().actorOf(Props.create(Table.class, iloscGraczy, iloscBotow, poczatkowe, wpisowe, stol));
	}
	
	public static void start(){
		stol.tell(new Start(), gra);
	}
	
	public static boolean tryJoin(String name){
		String result = null;
    	try{
			result = (String)Await.result(ask(stol ,new Join(name), 1000), Duration.create(1, SECONDS));
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
    	
    	if(result.equals("Niezajete")){
    		return true;
    	}
		return false;
	}
	
	public static boolean join(String name, WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){
		if(iloscObecnych < iloscGraczy){
			++iloscObecnych;
			stol.tell(new AddPlayer(name, in, out), gra);
			return true;
		}
		return false;
	}
	
	public void onReceive(Object msg){
		
	}
	
	public static ActorRef getStol(){
		return stol;
	}
	
	public static int getObecnych(){
		return iloscObecnych;
	}
	
}